import { useFetch } from "#app";

import { isArray } from "~/utils/tool";

export const useServerRequest = (url, opts) => {
  const token = useCookie("token");
  const runtimeConfig = useRuntimeConfig();

  const defaultOptions = {
    baseURL: runtimeConfig.public.baseUrl,
    onRequest({ options }) {
      options.headers = options.headers || {};
      if (token.value) {
        options.headers['x-token'] = token.value;
      }
    },
    onResponse({ response }) {
      if (+response.status === 200 && +response._data.code !== 0) {
        process.client && ElMessage.error(response._data.msg);
      }
    },
    onResponseError({ response }) {
      process.client &&
        ElMessage.error(
          isArray(response._data.msg)
            ? response._data.msg[0]
            : response._data.msg
        );
    },
  };

  return useFetch(url, { ...defaultOptions, ...opts });
};
